package org.myy.learn.aaa.a_哈希;

import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;

import java.util.*;

@Slf4j
public class 字母异位词分组 {
    public static List<List<String>> groupAnagrams(String[] strs) {
        int n = strs.length;
        //if (n == 0){return groupAnagrams;}  没必要
        Map<String, List<String>> map = new HashMap<>();
        for (int i=0; i<n; i++){
            if (!StringUtils.hasText(strs[i])){continue;}
            char[] str = strs[i].toCharArray();
            Arrays.sort(str);
            //String key = str.toString();   getClass().getName() + "@" + Integer.toHexString(hashCode());
            //在操作字符数组时，永远不要用 toString() 获取内容
            String key = new String(str);  //区别在哪里
            List<String> list = map.getOrDefault(key, new ArrayList<>());
            list.add(strs[i]);
            map.put(key, list);
        }

//        //方案1  collection<List<String>>,直接转换，collection ==> ArrayList
//        new ArrayList<>(map.values());   //new一个对象必须是ArrayList，不能是List。因为List是abstract
//        //方案2  流式编程，数据处理
//        map.values().stream().filter(list -> !list.isEmpty()).collect(Collectors.toList());
        return new ArrayList<>(map.values());   //new一个对象必须是ArrayList，不能是List。因为List是abstract
    }

    public static void main(String[] args) {
        String[] strs = new String[]{"eat", "tea", "tan", "ate", "nat", "bat"};
        List<List<String>> groupAnagrams = groupAnagrams(strs);
        log.info("执行结束，groupAnagrams={}", groupAnagrams);

        //测试toString
        String[] a = new String[]{"eat"};
        String[] b = new String[]{"eat"};
        log.info("执行结束，是否相等={}", a.toString().equals(b.toString()));
    }
}
